﻿using Core.Caching;
using Core.Pipeline.Attributes;
using Finbuckle.MultiTenant.Abstractions;
using Infrastructure.Tenant;
using MediatR;
using Microsoft.Extensions.Logging;
using ZiggyCreatures.Caching.Fusion;

namespace Infrastructure.Pipeline;

/// <summary>
/// 删除缓存
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
[PipelineOrder(2)]
public class CacheInvalidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
      where TRequest : ICacheInvalidatorRequest<TResponse>
{
    private readonly IFusionCache _cache;
    private readonly ILogger<CacheInvalidationBehaviour<TRequest, TResponse>> _logger;
    private readonly IMultiTenantContextAccessor<BoilerplateTenantInfo> _multiTenantContextAccessor;

    public CacheInvalidationBehaviour(
        IFusionCache cache,
        ILogger<CacheInvalidationBehaviour<TRequest, TResponse>> logger
,
        IMultiTenantContextAccessor<BoilerplateTenantInfo> multiTenantContextAccessor)
    {
        _cache = cache;
        _logger = logger;
        _multiTenantContextAccessor = multiTenantContextAccessor;
    }
    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        var cacheProxy = _multiTenantContextAccessor.MultiTenantContext.TenantInfo?.Id!;
        _logger.LogDebug("{Name} 缓存过期 {@Request}", nameof(request), request);
        var response = await next().ConfigureAwait(false);
        if (!string.IsNullOrEmpty(request.CacheKey))
        {
            _cache.Remove(request.CacheKey.GetCacheKey(cacheProxy));
            _logger.LogDebug("缓存键值 {CacheKey} 已从缓存中删除", request.CacheKey);
        }
        if (request.Tags != null && request.Tags.Any())
        {
            foreach (var tag in request.Tags.GetCacheTags(cacheProxy))
            {
                await _cache.RemoveByTagAsync(tag);
                _logger.LogDebug("缓存标签 {CacheTag} 已从缓存中删除", tag);
            }
        }
        return response;
    }
}
